package com.quanyan.ic.protocol.codec;

import com.quanyan.ic.protocol.MessageType;
import com.quanyan.ic.protocol.codec.protobuf.ICMessageProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhuo.shi on 2017/6/7.
 * +---------------+               +--------+---------------+
 * | Protobuf Data |-------------->| Length  | Protobuf Data |
 * |  ( x bytes)   |               | 4 bytes |  (x bytes)    |
 * +---------------+               +--------+---------------+
 */
public class ICMessageEncoder extends MessageToByteEncoder<ICMessageProto.ICMessage> {

    private Logger logger = LoggerFactory.getLogger(ICMessageEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ICMessageProto.ICMessage icMessage, ByteBuf byteBuf) throws Exception {

        byteBuf.writeInt(icMessage.toByteArray().length);       //在protobuf data前面写入4个字节的int，标识protobuf data的长度
        byteBuf.writeBytes(icMessage.toByteArray());            //写入protobuf data

        if (icMessage.getHeader().getType() == MessageType.SERVICE_REQ.value()) {
            logger.info("server send Cmd msg: {}", icMessage);
        }
    }
}
